package com.yt.user.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.user.models.bo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import com.yt.user.models.service.ICustomerInfoService;
import com.yt.user.models.dto.CustomerInfoDTO;
import com.yt.user.models.vo.CustomerInfoVO;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;

/**
 * 客户信息控制器
 *
 * @author yzz
 * @Date 2025-09-03 14:13:56
 */

@RestController
@RequestMapping("/api/customerInfo")
@Slf4j
@Api(value = "CustomerInfoApiController",tags = "客户信息Api接口")
public class CustomerInfoApiController {

    @DubboReference
    private ICustomerInfoService customerInfoService;

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<CustomerInfoDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        CustomerInfoDTO dto = customerInfoService.selectById(id);

        return new Result<>(dto);
    }
    
    @PostMapping("/list")
    @ApiOperation(value = "获取所有客户信息列表", notes = "获取所有客户信息列表")
    public Result<List<CustomerInfoVO>> getAllCustomers() {
        Wrapper<CustomerInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("is_del", 0);
        List<CustomerInfoDTO> customers = customerInfoService.selectList(wrapper);
        List<CustomerInfoVO> customerVOs = customers.stream().map(dto -> {
            CustomerInfoVO vo = new CustomerInfoVO();
            vo.setId(dto.getId());
            vo.setRevision(dto.getRevision());
            vo.setType(dto.getType());
            vo.setCustomerName(dto.getCustomerName());
            vo.setAddress(dto.getAddress());
            vo.setPhone(dto.getPhone());
            vo.setStatus(dto.getStatus());
            vo.setIsDel(dto.getIsDel());
            vo.setCreateTime(dto.getCreateTime());
            vo.setUpdateTime(dto.getUpdateTime());
            return vo;
        }).collect(Collectors.toList());
        
        return new Result<>(customerVOs);
    }
    
    @PostMapping("/update")
    @ApiOperation(value = "编辑客户信息", notes = "编辑客户信息")
    public Result<Boolean> updateCustomer(@RequestBody CustomerUpdateRequest request) {
        if (request.getId() == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        CustomerInfoDTO dto = customerInfoService.selectById(request.getId());
        if (dto == null) {
            return new Result<>(CodeEnum.FAIL_100003);
        }

        // 将请求参数复制到DTO对象中
        BeanUtils.copyProperties(request, dto);
        dto.setUpdateTime(new Date());
        
        boolean result = customerInfoService.updateById(dto);
        return new Result<>(result);
    }
    
    @PostMapping("/updateStatus")
    @ApiOperation(value = "更新客户状态", notes = "根据客户ID更新客户状态")
    public Result<Boolean> updateCustomerStatus(@RequestBody CustomerStatusUpdateRequest request) {
        if (request.getId() == null || request.getStatus() == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        
        CustomerInfoDTO dto = customerInfoService.selectById(request.getId());
        if (dto == null) {
            return new Result<>(CodeEnum.FAIL_100003);
        }
        
        dto.setStatus(request.getStatus());
        dto.setUpdateTime(new Date()); // 更新时间
        boolean result = customerInfoService.updateById(dto);
        
        return new Result<>(result);
    }
    
    @PostMapping("/delete")
    @ApiOperation(value = "逻辑删除客户信息", notes = "逻辑删除客户信息")
    public Result delete(@RequestBody CustomerDeleteRequest request) {
        if (request.getId() == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        
        CustomerInfoDTO dto = customerInfoService.selectById(request.getId());
        if (dto == null) {
            return new Result<>(CodeEnum.FAIL_100003);
        }
        
        // 设置逻辑删除标识为已删除(1)
        dto.setIsDel(1);
        dto.setUpdateTime(new Date()); // 更新时间
        boolean flag = customerInfoService.updateById(dto);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100009);
        }
    }

    @ApiOperation(value = "客户信息列表",notes = "客户信息列表")
    @PostMapping("/queryPageList")
    public Result<Page<CustomerInfoDTO>> queryPageList(CustomerInfoBO bo){
        Wrapper<CustomerInfoDTO> wrapper = new EntityWrapper<>();
                if (bo.getStatus() != null){
                    wrapper.eq("status", bo.getStatus());
                }
        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<CustomerInfoDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = customerInfoService.selectPage(page, wrapper);

        return new Result<>(page);
    }

    @PostMapping("/getByName")
    @ApiOperation(value = "根据客户姓名查找", notes = "根据客户姓名查找")
    @ApiImplicitParam(name = "customerName", value = "客户姓名", required = true, paramType = "query", dataType = "String")
    public Result<List<CustomerInfoVO>> getByName(@RequestParam("customerName") String customerName) {
        if (customerName == null || customerName.trim().isEmpty()) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        Wrapper<CustomerInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("is_del", 0);
        wrapper.like("customer_name", customerName);
        List<CustomerInfoDTO> customers = customerInfoService.selectList(wrapper);
        List<CustomerInfoVO> customerVOs = customers.stream().map(dto -> {
            CustomerInfoVO vo = new CustomerInfoVO();
            vo.setId(dto.getId());
            vo.setRevision(dto.getRevision());
            vo.setType(dto.getType());
            vo.setCustomerName(dto.getCustomerName());
            vo.setAddress(dto.getAddress());
            vo.setPhone(dto.getPhone());
            vo.setStatus(dto.getStatus());
            vo.setIsDel(dto.getIsDel());
            vo.setCreateTime(dto.getCreateTime());
            vo.setUpdateTime(dto.getUpdateTime());
            return vo;
        }).collect(Collectors.toList());

        return new Result<>(customerVOs);
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加客户信息", notes = "添加客户信息，会自动设置状态为启用、未删除，并设置创建时间和更新时间")
    public Result<Boolean> addCustomer(@RequestBody CustomerInfoSaveBO saveBO) {
        // 设置默认值：status=1(启用), isDel=0(未删除)
        saveBO.setStatus(1);
        saveBO.setIsDel(0);
        boolean result = customerInfoService.add(saveBO);
        return new Result<>(result);
    }

    @PostMapping("/login")
    @ApiOperation(value = "客户登录", notes = "客户登录接口")
    public Result<CustomerInfoVO> login(@RequestBody CustomerLoginRequest loginRequest) {
        // 参数校验
        if (loginRequest.getPhone() == null || loginRequest.getPhone().trim().isEmpty()) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "手机号不能为空");
        }
        
        // 查询客户信息
        Wrapper<CustomerInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("phone", loginRequest.getPhone());
        wrapper.eq("status", 1); // 只查询启用状态的客户
        wrapper.eq("is_del", 0); // 只查询未删除的客户
        
        List<CustomerInfoDTO> customerList = customerInfoService.selectList(wrapper);
        
        // 判断客户是否存在
        if (customerList == null || customerList.isEmpty()) {
            return new Result<>(CodeEnum.FAIL_100003.getCode(), "客户不存在或已被禁用");
        }
        
        CustomerInfoDTO customerInfo = customerList.get(0);
        
        // 登录成功，返回客户信息
        CustomerInfoVO customerInfoVO = new CustomerInfoVO();
        BeanUtils.copyProperties(customerInfo, customerInfoVO);
        
        return new Result<>(CodeEnum.SUCCESS.getCode(), "登录成功", customerInfoVO);
    }
}